package com.zq.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zq.pojo.JwtToken;
import com.zq.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * 过滤器拦截请求的入口方法
     * 是否允许访问，如果带有 token，则对 token 进行检查，否则直接拒绝
     * 如果返回true,就流转到下一个链式调用
     * 如果返回false，就会流转到onAccessDenied方法
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("isAccessAllowed");
        if (isLoginAttempt(request, response)) {//请求头包含Token
            try { //如果存在，则进入 executeLogin 方法，检查 token 是否正确
                executeLogin(request, response);
                return true;
            }catch (AuthenticationException e){
                handlerLoginException(response,e);
            } catch (Exception e) {
                handlerLoginException(response,new AuthenticationException("error"));
            }
        }else {
            handlerLoginException(response,new AuthenticationException("token无效"));
        }
        //如果请求头不存在 Token，直接返回 false
        return false;
    }

    //拒绝访问的请求
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }

    /**
     * 判断用户是否已经登录
     * 检测 header 里面是否包含 Token 字段
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        log.info("isLoginAttempt");
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        return token != null;
    }

    /**
     * Shiro认证操作
     * executeLogin实际上就是先调用createToken来获取token，这里我们重写了这个方法，就不会自动去调用createToken来获取token
     * 然后调用getSubject方法来获取当前用户再调用login方法来实现登录
     * 这也解释了我们为什么要自定义jwtToken，因为我们不再使用Shiro默认的UsernamePasswordToken了。
     * */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception{
        log.info("executeLogin");
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        JwtToken jwt = new JwtToken(token);
        getSubject(request, response).login(jwt);
        return true;
    }

    /**
     * 在JwtFilter处理逻辑之前，进行跨域处理
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.info("preHandle");
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse res= (HttpServletResponse) response;
        res.setHeader("Access-control-Allow-Origin",req.getHeader("Origin"));
        res.setHeader("Access-control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE");
        res.setHeader("Access-control-Allow-Headers",req.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            res.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 在token校验无效之后返回json信息，这里使用jackson配合原生servlet写法，直接抛出的异常会被jwt过滤器捕获并自己处理，使用全局异常处理无效
     * @param response
     * @param e
     */
    private void handlerLoginException(ServletResponse response,AuthenticationException e){
        response.setContentType("application/json;charset=utf-8");
        try(PrintWriter writer = response.getWriter()){
            ResultVo<Object> resultVo=ResultVo.invalid(e.getMessage());
            ObjectMapper objectMapper=new ObjectMapper();
            writer.print(objectMapper.writeValueAsString(resultVo));
        }catch (IOException ignored){
        }
    }
}
